#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>

const QString& SERVER_IP="127.0.0.1";
const quint16 SER_PORT=9090;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //设置窗口标题
    this->setWindowTitle("客户端");
    //创建socked对象并连接
    socket=new QTcpSocket(this);
    socket->connectToHost(SERVER_IP,SER_PORT);//非阻塞
    //连接信号槽处理响应
    connect(socket,&QTcpSocket::readyRead,this,[this](){
        ui->listWidget->addItem("客户端说:"+socket->readAll());
    });
    //等待连接结果
    if(socket->waitForConnected()==false)
    {
        QMessageBox::critical(this,"连接服务器出错",socket->errorString());
        exit(-1);
    }



}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    //获取到输入框内容
    const QString& text=ui->lineEdit->text();
    //发送到服务器
    socket->write(text.toUtf8());
    //把发的信息显示到界面上
    ui->listWidget->addItem("客户端说:"+text);
    //清空输入框
    ui->lineEdit->setText("");
}
